<!DOCTYPE html>
<html lang="zh" class="no-js">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="description" content="book">
<meta name="generator" content="Paradox, paradox-material-theme=0.6.0, mkdocs-material=3.0.3">

<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="">
<meta name="lang:search.pipeline.stopwords" content="true">
<meta name="lang:search.pipeline.trimmer" content="true">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">


<meta name="description" content="book">
<link rel="shortcut icon" href="../assets/images/favicon.png">
<title>常用指令（Directives）</title>
<link rel="stylesheet" href="../assets/stylesheets/application.451f80e5.css">
<link rel="stylesheet" href="../assets/stylesheets/application-palette.22915126.css">
<meta name="theme-color" content="#009688" />
<link rel="stylesheet" href="../lib/material__tabs/dist/mdc.tabs.min.css">
<link rel="stylesheet" href="../lib/prettify/prettify.css">
<script src="../assets/javascripts/modernizr.1aa3b519.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,700|Roboto+Mono">
<style>
body,input{font-family:"Roboto","Helvetica Neue",Helvetica,Arial,sans-serif}
code,kbd,pre{font-family:"Roboto Mono","Courier New",Courier,monospace}
</style>
<link rel="stylesheet" href="../assets/fonts/font-awesome.css">
<link rel="stylesheet" href="../assets/fonts/material-icons.css">
<link rel="stylesheet" href="../assets/stylesheets/paradox-material-theme.css">
</head>
<body
data-md-color-primary="teal"
data-md-color-accent="indigo"
>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer" autocomplete="off">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search" autocomplete="off">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../routing-dsl/common-directive.html" title="常用指令（Directives）" class="md-header-nav__button md-logo">
<i class="md-icon">local_library</i>
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
常用指令（Directives）
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" name="search">
<input type="text" class="md-search__input" name="query" placeholder="Search" autocapitalize="off" autocorrect="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">&#xE5CD;</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>

</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/yangbajing/scala-web-development"
title="Go to repository"
class="md-source"
data-md-source="github">
<div class="md-source__icon">
<i class="fa fa-github"></i>
</div>
<div class="md-source__repository">
yangbajing/scala-web-development
</div>
</a>

</div>
</div>
</div>
</nav>
</header>

<div class="md-container">
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0" style="visibility: hidden">
<label class="md-nav__title md-nav__title--site" for="drawer">
<a href="../routing-dsl/common-directive.html" title="常用指令（Directives）" class="md-nav__button md-logo">
<span class="md-nav__button md-logo">
<i class="md-icon">local_library</i>
</a>
<a href="../routing-dsl/common-directive.html" title="常用指令（Directives）">
常用指令（Directives）
</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/yangbajing/scala-web-development"
title="Go to repository"
class="md-source"
data-md-source="github">
<div class="md-source__icon">
<i class="fa fa-github"></i>
</div>
<div class="md-source__repository">
yangbajing/scala-web-development
</div>
</a>

</div>
<ul>
</ul>
<nav class="md-nav md-nav--secondary">
<label class="md-nav__title" for="__toc">Table of contents</label>
<ul>
  <li><a href="../routing-dsl/common-directive.html#常用指令-directives-" class="header">常用指令（Directives）</a>
  <ul>
    <li><a href="../routing-dsl/common-directive.html#methoddirectives" class="header">MethodDirectives</a></li>
    <li><a href="../routing-dsl/common-directive.html#parameterdirectives-formfielddirectives" class="header">ParameterDirectives，FormFieldDirectives</a></li>
    <li><a href="../routing-dsl/common-directive.html#marshallingdirectives" class="header">MarshallingDirectives</a></li>
    <li><a href="../routing-dsl/common-directive.html#fileuploaddirectives" class="header">FileUploadDirectives</a></li>
    <li><a href="../routing-dsl/common-directive.html#cookiedirectives" class="header">CookieDirectives</a></li>
  </ul></li>
</ul>
</nav>

</nav>
<ul style="display: none">
<li class="md-nav__item md-version" id="project.version">
<label class="md-nav__link" for="__version">
<i class="md-icon" title="Version">label_outline</i> 1.0.0
</label>
</li>
</ul>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<label class="md-nav__title" for="__toc">Table of contents</label>
<ul>
  <li><a href="../routing-dsl/common-directive.html#常用指令-directives-" class="header">常用指令（Directives）</a>
  <ul>
    <li><a href="../routing-dsl/common-directive.html#methoddirectives" class="header">MethodDirectives</a></li>
    <li><a href="../routing-dsl/common-directive.html#parameterdirectives-formfielddirectives" class="header">ParameterDirectives，FormFieldDirectives</a></li>
    <li><a href="../routing-dsl/common-directive.html#marshallingdirectives" class="header">MarshallingDirectives</a></li>
    <li><a href="../routing-dsl/common-directive.html#fileuploaddirectives" class="header">FileUploadDirectives</a></li>
    <li><a href="../routing-dsl/common-directive.html#cookiedirectives" class="header">CookieDirectives</a></li>
  </ul></li>
</ul>
</nav>

</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset">
<div class="md-content__searchable">
<h1><a href="#常用指令-directives-" name="常用指令-directives-" class="anchor"><span class="anchor-link"></span></a>常用指令（Directives）</h1>
<h2><a href="#methoddirectives" name="methoddirectives" class="anchor"><span class="anchor-link"></span></a>MethodDirectives</h2>
<p>HTTP方法指令用于匹配HTTP method，当请求不符合时将被拒绝，并返回 <strong>405 Method Not Allowed</strong>。常用预定义指令有：</p>
<ul>
  <li><code>get</code>：匹配HTTP的GET方法</li>
  <li><code>post</code>：匹配HTTP的POST方法</li>
  <li><code>put</code>：匹配HTTP的PUT方法</li>
  <li><code>delete</code>：匹配HTTP的DELETE方法</li>
</ul>
<h3><a href="#抽取httpmethod" name="抽取httpmethod" class="anchor"><span class="anchor-link"></span></a>抽取HttpMethod</h3>
<p>除了在路由上匹配某个HTTP方法外，我们还可以抽取方法（HttpMethod），这个使用 <code>def extractMethod: Directive1[HttpMethod]</code>指令。示例如下：</p>
<pre class="prettyprint"><code class="language-scala">val route =
  get {
    complete(&quot;This is a GET request.&quot;)
  } ~
    extractMethod { method =&gt;
      complete(s&quot;This ${method.name} request, clearly is not a GET!&quot;)
    }

// tests:
Get(&quot;/&quot;) ~&gt; route ~&gt; check {
  responseAs[String] shouldEqual &quot;This is a GET request.&quot;
}

Put(&quot;/&quot;) ~&gt; route ~&gt; check {
  responseAs[String] shouldEqual &quot;This PUT request, clearly is not a GET!&quot;
}
Head(&quot;/&quot;) ~&gt; route ~&gt; check {
  responseAs[String] shouldEqual &quot;This HEAD request, clearly is not a GET!&quot;
}
</code></pre>
<h3><a href="#自定义httpmethod" name="自定义httpmethod" class="anchor"><span class="anchor-link"></span></a>自定义HttpMethod</h3>
<p>当你需要使用非标准的Http方法时，可以通过<code>HttpMethod.custom</code>来自定义。</p>
<pre class="prettyprint"><code class="language-scala">import akka.http.scaladsl.settings.{ ParserSettings, ServerSettings }

// 自定义HTTP方法:
val BOLT = HttpMethod.custom(&quot;BOLT&quot;, safe = false,
  idempotent = true, requestEntityAcceptance = Expected)

// 添加自定义方法到设置里
val parserSettings = ParserSettings(system).withCustomMethods(BOLT)
val serverSettings = ServerSettings(system).withParserSettings(parserSettings)

val routes = extractMethod { method =&gt;
  complete(s&quot;This is a ${method.name} method request.&quot;)
}
val binding = Http().bindAndHandle(routes, host, port, settings = serverSettings)

val request = HttpRequest(BOLT, s&quot;http://$host:$port/&quot;, protocol = `HTTP/1.1`)
</code></pre>
<h3><a href="#overridemethodwithparameter" name="overridemethodwithparameter" class="anchor"><span class="anchor-link"></span></a>overrideMethodWithParameter</h3>
<pre class="prettyprint"><code class="language-scala">def overrideMethodWithParameter(paramName: String): Directive0
</code></pre>
<p><code>overrideMethodWithParameter</code>指令可以通过指定的请求参数来改变<code>HttpRequest</code>保存的请求HTTP方法。这在一些遗留项目或特殊环境下有用。比如：某些网络环境不支持<code>DELETE</code>、<code>PUT</code>方法，就可以通过如下的方式将一个带特定参数的请求转换成对应的<code>DELETE</code>或<code>PUT</code>请求。</p>
<pre class="prettyprint"><code class="language-scala">val route =
  overrideMethodWithParameter(&quot;method&quot;) {
    get {
      complete(&quot;This looks like a GET request.&quot;)
    } ~
      post {
        complete(&quot;This looks like a POST request.&quot;)
      }
  }

// tests:
Get(&quot;/?method=POST&quot;) ~&gt; route ~&gt; check {
  responseAs[String] shouldEqual &quot;This looks like a POST request.&quot;
}
Post(&quot;/?method=get&quot;) ~&gt; route ~&gt; check {
  responseAs[String] shouldEqual &quot;This looks like a GET request.&quot;
}

Get(&quot;/?method=hallo&quot;) ~&gt; route ~&gt; check {
  status shouldEqual StatusCodes.NotImplemented
}
</code></pre>
<h2><a href="#parameterdirectives-formfielddirectives" name="parameterdirectives-formfielddirectives" class="anchor"><span class="anchor-link"></span></a>ParameterDirectives，FormFieldDirectives</h2>
<p>TODO</p>
<h2><a href="#marshallingdirectives" name="marshallingdirectives" class="anchor"><span class="anchor-link"></span></a>MarshallingDirectives</h2>
<p>TODO</p>
<h2><a href="#fileuploaddirectives" name="fileuploaddirectives" class="anchor"><span class="anchor-link"></span></a>FileUploadDirectives</h2>
<p>TODO</p>
<h2><a href="#cookiedirectives" name="cookiedirectives" class="anchor"><span class="anchor-link"></span></a>CookieDirectives</h2>
<p>TODO</p>
</div>
<div>
<a href="https://github.com/yangbajing/scala-web-development/tree/master/book/src/main/paradox/routing-dsl/common-directive.md" title="Edit this page" class="md-source-file md-edit">
Edit this page
</a>
</div>
<div class="print-only">
<span class="md-source-file md-version">
1.0.0
</span>
</div>
</article>
</div>
</div>
</main>
<footer class="md-footer">
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
Powered by
<a href="https://github.com/lightbend/paradox">Paradox</a>
and
<a href="https://jonas.github.io/paradox-material-theme/">Paradox Material Theme</a>

</div>
<div class="md-footer-social">
<a href="https://github.com/yangbajing" class="md-footer-social__link fa fa-github"></a><a href="https://weibo.com/yangbajing" class="md-footer-social__link fa fa-globe"></a><a href="https://www.yangbajing.me/" class="md-footer-social__link fa fa-globe"></a>
</div>

</div>
</div>
</footer>

</div>
<script src="../assets/javascripts/application.583bbe55.js"></script>
<script src="../assets/javascripts/paradox-material-theme.js"></script>
<script>app.initialize({version:"0.17",url:{base:"../."}})</script>
<script type="text/javascript" src="../lib/prettify/prettify.js"></script>
<script type="text/javascript" src="../lib/prettify/lang-scala.js"></script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
window.prettyPrint && prettyPrint();
});
</script>
</body>
</html>
